package net.kaaass.poplan.ingress.api;

import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import com.mashape.unirest.request.body.RequestBodyEntity;
import com.sun.xml.internal.ws.api.FeatureConstructor;
import org.json.JSONObject;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Auth {
    String csrftoken = "";
    String v = "";
    String cookie = "";

    public Auth(String cookie) {
        this.cookie = cookie;
        Matcher m = Pattern.compile("csrftoken=([a-zA-Z0-9]*);").matcher(this.cookie);
        m.find();
        this.csrftoken = m.group(1);
        System.out.printf("Success fetch csrftoken - %s.\n", this.csrftoken);
        this.v = this.getVersion();
    }

    @FeatureConstructor
    public Auth(String usr, String passwd) {

    }

    public RequestBodyEntity authPost(String post, JSONObject json) {
        json.append("v", this.v);
        return Unirest.post(post).header("X-CSRFToken", this.csrftoken)
                .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2816.0 Safari/537.36")
                .header("Referer", "https://ingress.com/intel")
                .header("Cookie", this.cookie).body(json);
    }

    public String getVersion() {
        try {
            String data = Unirest.get("https://api.kaaass.net/ingress/version")
                    .queryString("cookie", this.cookie)
                    .asJson().getBody().getObject().getString("v");
            System.out.printf("Success in reading version - %s.\n",data);
            return data;
        } catch (UnirestException e) {
            e.printStackTrace();
            return null;
        }
    }
}
